import {MyNavBar} from '@/components'
import {MapContainer} from '@/common/js/amap-utils'
import {useEffect, useRef, useState} from 'react'
import {ActivityIndicator} from 'antd-mobile'
import {history} from 'umi'

import './index.less'
import {useDetailHook} from '@/hooks'
import {_getHouseAll} from './store'
import WindowInfo from './components/windowInfo'

function HouseMap() {
  const mapRef = useRef()

  const mapContainer = useRef()

  const {detailData: houseList, loading} = useDetailHook({func: _getHouseAll})

  const houseMarkers = useRef()

  const [ detailData, setDetailData ] = useState({})

  const [ isShow, setIsShow ] = useState(false)

  const isShowRef = useRef(false)

  const currentTarget = useRef(null)

  useEffect(() => {
    isShowRef.current = isShow
  }, [ isShow ])

  const initMap = () => {
    mapContainer.current = new MapContainer({
      target: mapRef.current
    })
    mapContainer.current.getLocation()
  }

  const handleClose = () => {
    setIsShow(false)
    mapContainer.current.setMarkerClustererIcon(currentTarget.current)
  }

  useEffect(() => {
    initMap()
  }, [])

  useEffect(() => {
    if (houseList && houseList.length) {
      houseMarkers.current = houseList.map(item => ({...item, iconName: 'house'}))
      mapContainer.current.addMarkerClusterer({
        data: houseMarkers.current, markerClickCallback: ({target}) => {
          currentTarget.current = target
          if (!mapContainer.current.isLastMarker(target)) {
            const data = target.getExtData()
            setDetailData(data)
            setIsShow(true)
          } else if (mapContainer.current.isLastMarker(target) && isShowRef.current) {
            setIsShow(false)
          }
          mapContainer.current.setMarkerClustererIcon(target)
        }
      })
    }
  }, [ houseList ])

  return (
    <div>
      <MyNavBar title='地图选房'/>
      {loading && <ActivityIndicator toast/>}
      <div className='house-map'>
        <div ref={mapRef} className='map-container'></div>
        <WindowInfo detailData={detailData} isShow={isShow} handleClose={handleClose}/>
      </div>
    </div>
  )
}

export default HouseMap
